<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    body{
      margin:0;
    }
  </style>
</head>
<body>
<form action="">
  <label for="">Path: </label>
  <select name="" id="text-path-select">
    <option value="none">none</option>
    <option value="#path1">path1</option>
    <option value="#path2">path2</option>
    <option value="#path3">path3</option>
  </select>
</form>
<div id="div1">
  <svg xmlns="http://www.w3.org/2000/svg" width="100vw" height="100vh" >
    <path id="path1" d="M 100 200 Q 200 100 300 200 T 500 200" stroke="rgb(0,255,0)" fill="none"/>
    <path id="path2" d="M 100 300 l 100-50 200 100 100-50" stroke="rgb(255,0,0)" fill="none"/>
    <path id="path3" d="M 100 400 A 400 300 0 0 0 500 400" stroke="rgb(0,0,255)" fill="none"/>

    <text id="text" x="100" y="100" style="font-size: 20px;">
      Text path scripting. <tspan id="tspan">动态使用路径文本</tspan>
    </text>
  </svg>
</div>
<script>
var SVG_NS = 'http://www.w3.org/2000/svg';
var XLINK_NS = 'http://www.w3.org/1999/xlink';

var select = document.getElementById('text-path-select');
var text = document.getElementById('text');
var tspan = document.getElementById('tspan');

function addTextPath() {
  var textPath = document.createElementNS(SVG_NS, 'textPath');
  while (text.firstChild){
    textPath.appendChild(text.firstChild);
  }
  text.appendChild(textPath);
}

function setTextPath(path) {
  var textPath = text.firstChild;
  // ↓直接setAttribute是不会生效的
  textPath.setAttributeNS(XLINK_NS, 'xlink:href', path);
  var pathElement = document.querySelector(path);
  tspan.setAttribute('fill', pathElement.getAttribute('stroke'));
}

function removeTextPath() {
  var textPath = text.firstChild;
  while (textPath.firstChild){
    text.appendChild(textPath.firstChild);
  }
  text.removeChild(textPath);
  tspan.removeAttribute('fill');
}

select.addEventListener('input', function(){
  var value = select.value;
  if (text.firstChild.tagName && text.firstChild.tagName.toLowerCase() === 'textpath'){
    if(value === 'none') removeTextPath();
    else setTextPath(value)
  }else {
    if (value !== 'none') {
      addTextPath();
      setTextPath(value);
    }
  }
})
</script>
</body>
</html>
